//Namespace Mashup
var Mashup = Mashup || {};
Mashup.init = function(){
	var jsonObjects;
	
	//Getter for producers
	this.getProd = function(){
		if(window.sessionStorage.producers != undefined){
			return JSON.parse(window.sessionStorage.producers);
		}
		return this.jsonObjects;
    };
    
    //Setter for producers
    this.setProd = function(object){
    	this.jsonObjects = object;
    	window.sessionStorage.producers = JSON.stringify(object);
    };
	
	this.populatePage();
};

/*--- Function to populate the page --- */
Mashup.init.prototype.populatePage = function(){
var that = this;

	$("#searchB").live("click", function(){
		that.searchClick();
	});
	
	$("#doSearch").live("click", function(){
		that.doSearch();
	});
	
	$("#showAll").live("click", function(){
		$("#prodUl").empty();
		that.populateListView("index.php?", true);
	});
	
	this.populateListView("index.php?");
};

/*--- ALT-Function to populate the ListView --- */
/*
Mashup.init.prototype.populateListViewalt = function(url){
	var that = this;
	
	if(url == undefined){
		$("#prodUl").append("<li><h3>Du måste ange sök kriterier!</h3></li>");
	}
	
	$.getJSON(url, function(json){
		that.setProd(json);
		
		$.each(json, function(key, value){
			if(key != "total"){
				$("#prodUl").append("<li><a href='#producent' class='row' id='" + key + "'>" + value.name + "</a></li>");
			}
		});
		
		$("ul").listview("refresh");
		
		$('.row').live("click", function() {
			that.onClick($(this).attr("id"))
		});
	});
};
*/

/*--- Function to populate the ListView --- */
Mashup.init.prototype.populateListView = function(url, rerender){
	var that = this;
	
	//Check if we have stored the producers localy
	if(that.getProd() != undefined && rerender != true){
		that.createProdLinks(that.getProd());
	}
	else{ //If not, get them from api
	
		if(url == undefined){
			$("#prodUl").append("<li><h3>Du måste ange sök kriterier!</h3></li>");
			$("ul").listview("refresh");
			return;
		}
	
		$.ajaxSetup({
			url : url,
			type : "GET"
		});
		
		$.ajax({
			success : function(data) {
	
				try {
					json = jQuery.parseJSON(data);
				} catch(e) {
					$("#prodUl").append("<li><h3>Inga träffar! Försök igen...</h3></li>");
					$("ul").listview("refresh");
					return;
				}
	
				that.setProd(json);
				that.createProdLinks(that.getProd());
			},
			statusCode : { 404: function(){
				$("#prodUl").append("<li><h3>Det verkar som att server inte svarar just nu!</h3></li>");
				$("ul").listview("refresh");
				return;
			}},
			error : function(object, error) {
				console.log("error loading data ---> " + object + " | " +error)
			}
		});
	}
};

/*--- Function to generate the links in the listview --- */
Mashup.init.prototype.createProdLinks = function(json){
	var that = this;
	
	$.each(json, function(key, value) {
		if(key != "total") {
			$("#prodUl").append("<li><a href='#producent' class='row' id='" + key + "'>" + value.name + "</a></li>");
		}
	});

	$("ul").listview("refresh");

	$('.row').live("click", function() {
		that.onClick($(this).attr("id"))
	});
}

/*--- Function to handle the onclick on rows in listview --- */
Mashup.init.prototype.onClick = function(key) {

	$("#producerDiv").empty();
	$("#map_canvas").empty();
	$("#map_canvas").append("<h2>Karta saknas för Producenten!</h2>");
	$("#producerDiv").append("<h2>" + this.getProd()[key].name + "</h2>");
	if(this.getProd()[key].logoURL != null){
		$("#producerDiv").append("<div><img src='http://matmarknad.se/images/" + this.getProd()[key].logoURL + "' style='max-width:460px;' /></div>");
	}
	$("#producerDiv").append("<p>" + this.getProd()[key].adress + "</p>");
	$("#producerDiv").append("<p>" + this.getProd()[key].zipcode + "</p>");
	$("#producerDiv").append("<p>" + this.getProd()[key].state + "</p>");
	if(this.getProd()[key].url != null){
		if(this.getProd()[key].url.substring(1, 4) != 'http'){
			$("#producerDiv").append("<p><a href='http://" + this.getProd()[key].url + "' >" + this.getProd()[key].url +"</a></p>")
		}
		else{
			$("#producerDiv").append("<p><a href='" + this.getProd()[key].url + "' >" + this.getProd()[key].url +"</a></p>");
		}
	}
	
	
	var url = "index.php?id=" + key;
	$.getJSON(url, function(json){
		var latlng = new google.maps.LatLng(json.position.latitude, json.position.longitude);
	    var myOptions = {
	      zoom: 9,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
		var marker = new google.maps.Marker({
      		position: latlng,
      		map: map,
      		title: json.position.description
  		});
	});
};

/*--- Function to handle the onclick on the search button --- */
Mashup.init.prototype.searchClick = function(){
	var urlG = "index.php?geo=true";
	$.getJSON(urlG, function(json){
		$.each(json, function(key, value){
			$('#select-choice-1').append("<option value="+ value.regionID +">"+ value.region +"</option>");
		});
	});
	
	var urlC = "index.php?category=true";
	$.getJSON(urlC, function(json){
		$.each(json, function(key, value){
			$('#select-choice-2').append("<option value="+ value.tagID +">"+ value.tagname +"</option>");
		});
	});
};

/*--- Function to handle the combined search --- */
Mashup.init.prototype.doSearch = function(){
	$("#prodUl").empty();
	
	var RegionId = $('#select-choice-1').selectmenu().val();
	var CategoryId = $('#select-choice-2').selectmenu().val();
	
	var url;
	
	if(CategoryId != "standard"){
		if(RegionId != "standard"){
			url = "index.php?filter=category/"+ CategoryId +"/region/" + RegionId;
		}
		else{
			url = "index.php?filter=category/"+ CategoryId;
		}
	}
	else if(RegionId != "standard"){
		url = "index.php?filter=region/"+RegionId;
	}
	
	if(url == undefined){
		//this.preventDefault
		$("<div class='ui-loader ui-overlay-shadow ui-body-b ui-corner-all'><h1>Du måste ange sökning!</h1></div>")
			.css({
			display: "block",
			top: window.pageYOffset + 100
			})
			.appendTo("body").delay(800)
			.fadeOut(4000, function () {
			$(this).remove();
			});
			window.location = "#searchPage";
			return false;
	}
	else{
		this.populateListView(url, true);
	}
};

/* -------- Starts the application --------- */
window.onload = function(){
	var app = new Mashup.init();
	//window.sessionStorage.clear();
}

